import { ClientMessage } from "@runtime/generate/message/ClientMessage";
import Long from "long";
import { reactive, UnwrapNestedRefs } from "vue";

/**
 * 硬件组件
 */
export default class DeviceComponent {
    private static instance: DeviceComponent = new DeviceComponent();
    /**
     * 硬件组件
     */
    public static get Default(): DeviceComponent {
        return this.instance;
    }

    constructor() {
        window.addEventListener('unload', this.Dispose.bind(this));
    }

    Dispose() {
        window.removeEventListener('unload', this.Dispose);
    }

    private devices: UnwrapNestedRefs<Map<number, ClientMessage.DeviceInformation>> = reactive(new Map());


    public get Devices(): UnwrapNestedRefs<Map<number, ClientMessage.DeviceInformation>> {
        return this.devices;
    }

    public Update(informations: ClientMessage.DeviceInformation | Array<ClientMessage.DeviceInformation>): void {
        if (Array.isArray(informations)) {
            for (const information of informations) {
                const id = Long.isLong(information.Id) ? information.Id.toNumber() : information.Id;
                const device = this.devices.get(id);
                if (device == undefined) {
                    this.devices.set(id, information);
                } else {
                    device.Name = information.Name;
                    device.Status = information.Status;
                    device.Description = information.Description;
                }
            }
        } else {
            const id = Long.isLong(informations.Id) ? informations.Id.toNumber() : informations.Id;
            const device = this.devices.get(id);
            if (device == undefined) {
                this.devices.set(id, informations);
            } else {
                device.Name = informations.Name;
                device.Status = informations.Status;
                device.Description = informations.Description;
            }
        }
    }
}